<template>
  <div id="Search">
    <div class="search">
      <search-item
        v-for="item in lists"
        @checkeds="change"
        :cate="item"
        :key="item.type"/>
    </div>

    <p class="clearfix search-filed" v-show="showClearBtn">
      <el-tag size="medium"
              closable
              @close="remove(item)"
              v-for="item in lists"
              :title="item.checksTitle"
              :key="item.type"
              v-if="item.checks.length > 0">{{ item.label }}：<span v-for="(key, index) in item.checks"><i
        v-if="index !== 0">，</i>{{ key.name }}</span>
      </el-tag>

      <el-button size="small" class="clear" @click="clear()">清除</el-button>
    </p>
  </div>
</template>

<script>
  import SearchItem from './SearchItem'

  export default {

    props: ['lists'],

    data () {
      return {
        showClearBtn: false
      }
    },

    mounted () {
      for (let item of this.lists) {
        if ((typeof item.model === 'string' && item.model) || (Array.isArray(item.model) && item.model.length > 0 )) {
          this.showClearBtn = true
          break
        }
      }
    },

    methods: {
      remove (item) {
        let checks = {}
        item.checks = []
        checks[item.type] = []
        this.$emit('change', {checks, item})
      },

      change (data) {
        let checks = {}
        let item = this.lists.find((item) => item.type === data.type)
        item.checks = data.data

        this.lists.forEach(item => {
          checks[item.type] = item.checks.map((item2) => item2.id)
        })

        this.$emit('change', {checks, item})
      },

      // 清除lists
      clear () {
        this.lists.forEach((item) => {
          item.checks = []
        })
        this.$emit('clear', this.lists)
      }
    },

    components: {
      SearchItem
    }
  }
</script>

<style type="text/scss" lang="scss" scoped="">
  @import "../../element-variables";

  .search {
    background-color: #fff;
    margin-bottom: 10px;
  }

  .search-filed {
    margin-bottom: 15px;
    .title {
      line-height: 30px;
    }
  }

  .clear {
    &:focus, &:active {
      background-color: #fff;
      color: #3e3e3e;
    }
  }

  .el-tag {
    background-color: #fff;
    border-color: #dedede;
    color: #3e3e3e;
    margin-right: 10px;
    padding-right: 25px;
    height: 30px;
    float: left;
    position: relative;

    &:hover {
      color: $--color-primary;
      border-color: $--color-primary;
    }
  }

  .el-button {
    border-color: #dedede;

    &:hover {
      background-color: $--color-primary;
      border-color: $--color-primary;
      color: #fff;
    }
  }

</style>
